#include "TcpServer.hpp"
#include "Log.hpp"
#include "Calculator.hpp"
#include"Daemon.hpp"
using namespace LogModule;
// 信息不完整，接着读
// 完整了就提取，然后反序列，创建request，提供给计算模块
using cal_t = std::function<Response(Request &req)>;

class Parse
{
public:
    Parse(cal_t cal)
        : _cal(cal) {};
    std::string Entry(std::string &package)
    {
        std::string message;
        std::string out;
        while (Decode(package, &message))
        {
            LOG(LogLevel::INFO)<<"Decode success"<<"\n"<<message;
            if (message.empty())
                break;
              
            Request request;;
            // 这里应该是反序列化，创建request，然后提供给计算模块
            if (!request.Deserialize(message))
                break;

                LOG(LogLevel::INFO)<<"Deserialize success"<<"\n";
            request.Print();
            Response resp = _cal(request);
            // 计算模块返回结果，序列化，返回给TcpServer

            std::string res;
            resp.Serialize(res);
            LOG(LogLevel::INFO)<<"serialize success"<<"\n"<<res;

                Encode(res);
                LOG(LogLevel::INFO)<<"Encode success"<<"\n"<<res;
            out += res;
        }
        return out;
    }

private:
    cal_t _cal;
};

int main()
{
    ENABLE_FILE_LOG();
    Daemon(false, false);;
    // Command cmd;
    // std::unique_ptr<TcpServer> ts_ptr=std::make_unique<TcpServer>([&cmd](std::string message){return cmd.Execute(message);});
    // 计算模块
    Calculator cal;
    // 解析模块
    auto handler = [&cal](Request &req)
    { return cal.Execute(req); };
    Parse parse(handler);
    // 通信模块
    std::unique_ptr<TcpServer> ts_ptr = std::make_unique<TcpServer>([&parse](std::string &message)
                                                                    { return parse.Entry(message); });
    ts_ptr->InitServer();
    ts_ptr->Start();
}